package crud

import (
	"github.com/emicklei/go-restful"
	"github.com/jackc/pgx"
	"github.com/jinzhu/gorm"
	"gitlab.com/adapt-karaoke-project/backend/model"
	"gitlab.com/adapt-karaoke-project/backend/service/base"
	"gitlab.com/adapt-karaoke-project/backend/config"
)

type CrudService struct {
	dbService base.DBService
}

func NewCrudService(pool *pgx.ConnPool, db *gorm.DB) *CrudService {
	return &CrudService{
		dbService: *base.NewDBService(pool, db),
	}
}

func (cs *CrudService) Register(container *restful.Container) {
	ws := new(restful.WebService)
	ws.Path("/api")
	ws.Route(ws.GET("/records").
		Produces(restful.MIME_JSON).
		To(cs.GetRecords))
	ws.Route(ws.GET("/songs").
		Produces(restful.MIME_JSON).
		To(cs.GetAllSongs))
	ws.Route(ws.GET("/song/{song-id}").
		To(cs.GetSongById).
		Param(restful.PathParameter("song-id", "id of song")).
		Produces(restful.MIME_JSON))
	ws.Route(ws.GET("/record/{record-id}").
		To(cs.GetRecordById).
		Param(restful.PathParameter("record-id", "id of record")).
		Produces(restful.MIME_JSON))
	ws.Route(ws.POST("/records").To(cs.PostRecordStub))
	ws.Route(ws.POST("/wechat/sessions").
		To(cs.StubWechatLogin).
		Consumes(restful.MIME_JSON).
		Produces(restful.MIME_JSON))
	ws.Route(ws.DELETE("/sessions").To(cs.StubLogout))
	ws.Route(ws.GET("/user").To(cs.StubCurrentUserInfo).Produces(restful.MIME_JSON))
	//ADD
	ws.Route(ws.GET("/add").To(cs.NoUSe).Produces(restful.MIME_JSON))
	container.Add(ws)
}

func (cs *CrudService) Init(cfg config.InitConfig) {
	cs.dbService.DB.AutoMigrate(model.Record{}, model.Song{}, model.User{})
	if cfg.AddStubData {
		cs.initStubUsers()
		cs.initStubSongs()
		cs.initStubRecords()
	}
}
